Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
What should I use as a key for "row" elements in react?

I have a gallery that displays a number of books per row. This gallery takes an array of books as a prop and uses "itemsPerRow" prop to chunk the books into a 2 dimensional array and then loops through all the books to display the books in a grid-like structure.

export default function Gallery({ items, itemsPerRow, renderLink }) {

    itemsPerRow = itemsPerRow ?? 3
    const rows = chunk(items, itemsPerRow)

    const renderEmptyItems = (itemsToRender) => {
        const items = []
        for(let n = itemsToRender; n > 0; n--) {
            items.push(<GalleryItem key={`empty_${n}`} empty/>)
        }

        return items
    }

    return (
        <div>
        {
            rows.map((row, index) => (
                <div key={index} className="tile is-ancestor">

                    {row.map(item => <GalleryItem key={item.id} renderLink={renderLink} {...item}/>)}

                    {/* Add empty gallery items to make rows even */}
                    {index + 1 === rows.length && renderEmptyItems(itemsPerRow - row.length)}
                </div>
            ))
        }
        </div>
    )
}

However, unless I give each div representing a row a key, react complains about the lack of keys. As I understand it, using the index as a key doesn't really help react and should be avoided. So what should I use as a key here <div key={index} className="tile is-ancestor"> instead of the index?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use a unique identifier (book.id, maybe book.title if it's unique) for the key props. If your data does not have a unique identifier, it's okay to use index.

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to specify a value that uniquely identify the item, such as the id. You can read more about keys in the documentation.

Also it is not recommended to use indexes as keys if the order of your data can change, as React relies on the keys to know which components to re-render, the documentation I linked explains that further.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the unique_identifier which differentiate each of the documents(probably, you should pass the document _id as a key prop in the row components)

 <div className="row">
      {notes.map((item) => {
        return (
          <div key={note._id} className="col-md-6">
            <Component item={item} />
          </div>
        );
      })}
  </div>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda